package com.csc531.edit;

import java.util.ArrayList;
import java.util.Calendar;

import android.app.Activity;
import android.app.DatePickerDialog;
import android.app.Dialog;
import android.app.TimePickerDialog;
import android.database.Cursor;
import android.os.Bundle;
import android.util.Log;
import android.view.View;
import android.widget.ArrayAdapter;
import android.widget.AutoCompleteTextView;
import android.widget.Button;
import android.widget.DatePicker;
import android.widget.EditText;
import android.widget.TextView;
import android.widget.TimePicker;

import com.csc531.R;
import com.csc531.adapters.ClassesDbAdapter;


/**
 * @author Javier Figueroa
 * Displays the view to edit or create a new task
 *
 */
public class ClassesEdit extends Activity 
{
	//logging
	private static final String TAG = "classesedit";

	static ArrayList<String> _coursesList;

	//View fields
	AutoCompleteTextView _taskCourseText;
	private EditText _taskTitleText;
	private TextView _taskDueDate;
	private EditText _taskBodyText;

	//database 
	private Long _rowId;
	private ClassesDbAdapter _mDbHelper;

	// date and time
	private int _year;
	private int _month;
	private int _day;
	private int _hour;
	private int _minute;

	static final int TIME_DIALOG_ID = 0;
	static final int DATE_DIALOG_ID = 1;

	private Button _confirmButton;
	
	/* (non-Javadoc)
	 * @see android.app.Activity#onCreate(android.os.Bundle)
	 */
	@Override
	protected void onCreate(Bundle savedInstanceState) 
	{
		super.onCreate(savedInstanceState);
		_mDbHelper = new ClassesDbAdapter(this);
		_mDbHelper.open();
		setContentView(R.layout.class_edit);

		populateCoursesArrayList();

		ArrayAdapter<String> adapter = new ArrayAdapter<String>(this, android.R.layout.simple_dropdown_item_1line, _coursesList);
		_taskCourseText = (AutoCompleteTextView) findViewById(R.id.edit);
		_taskCourseText.setAdapter(adapter);
		_taskTitleText = (EditText) findViewById(R.id.title);
		_taskDueDate = (TextView) findViewById(R.id.dateDisplay);
		displayDateField();
		_taskBodyText = (EditText) findViewById(R.id.body);

		_confirmButton = (Button) findViewById(R.id.confirm);
		dealWithTaskData(savedInstanceState);
	}

	/**
	 * @param confirmButton the confirm button
	 * @param savedInstanceState application saved instance
	 */
	private void dealWithTaskData(Bundle savedInstanceState) 
	{
		_rowId = savedInstanceState != null ? savedInstanceState.getLong(ClassesDbAdapter.KEY_ROWID) : null;

		if(_rowId == null) {
			Bundle extras = getIntent().getExtras();
			_rowId = extras != null ? extras.getLong(ClassesDbAdapter.KEY_ROWID) : null;
		}
		
		populateFields();
		
		_confirmButton.setOnClickListener(new View.OnClickListener() 
		{
			public void onClick(View view) 
			{
				setResult(RESULT_OK);
				finish();
			}

		});
	}

	/**
	 * Prints date field to the screen
	 */
	private void displayDateField() 
	{
		Button pickDate = (Button) findViewById(R.id.pickDate);
		pickDate.setOnClickListener(new View.OnClickListener() 
		{
			public void onClick(View v) 
			{
				showDialog(DATE_DIALOG_ID);
			}
		});

		Button pickTime = (Button) findViewById(R.id.pickTime);
		pickTime.setOnClickListener(new View.OnClickListener() 
		{
			public void onClick(View v) 
			{
				showDialog(TIME_DIALOG_ID);
			}
		});

		final Calendar c = Calendar.getInstance();
		_year = c.get(Calendar.YEAR);
		_month = c.get(Calendar.MONTH);
		_day = c.get(Calendar.DAY_OF_MONTH);
		_hour = c.get(Calendar.HOUR_OF_DAY);
		_minute = c.get(Calendar.MINUTE);

		updateDisplay();
	}

	/**
	 * Populates an array list with the courses from the database
	 */
	private void populateCoursesArrayList() 
	{
		_coursesList = new ArrayList<String>();
		Cursor cursor = _mDbHelper.fetchAllCourses();
		startManagingCursor(cursor);

		for(int i = 0 ; i < cursor.getCount() ; i++) 
		{
			_coursesList.add(cursor.getString(0));
			cursor.moveToNext();
		}
	}

	/**
	 * Populates the field of the view when editing an existent task
	 */
	private void populateFields() 
	{
		if (_rowId != null) 
		{
			Cursor note = _mDbHelper.fetchTask(_rowId);
			startManagingCursor(note);

			_taskCourseText.setText(note.getString(
					note.getColumnIndexOrThrow(ClassesDbAdapter.KEY_COURSE)));
			_taskTitleText.setText(note.getString(
					note.getColumnIndexOrThrow(ClassesDbAdapter.KEY_TITLE)));
			_taskDueDate.setText(note.getString(
					note.getColumnIndexOrThrow(ClassesDbAdapter.KEY_DUEDATE)));
			_taskBodyText.setText(note.getString(
					note.getColumnIndexOrThrow(ClassesDbAdapter.KEY_BODY)));
		}
	}

	/* (non-Javadoc)
	 * @see android.app.Activity#onPause()
	 */
	@Override
	protected void onPause() 
	{
		// TODO Auto-generated method stub
		super.onPause();
		saveState();
	}

	/* (non-Javadoc)
	 * @see android.app.Activity#onResume()
	 */
	@Override
	protected void onResume() 
	{
		// TODO Auto-generated method stub
		super.onResume();
		populateFields();
	}

	/* (non-Javadoc)
	 * @see android.app.Activity#onSaveInstanceState(android.os.Bundle)
	 */
	@Override
	protected void onSaveInstanceState(Bundle outState) 
	{
		// TODO Auto-generated method stub
		super.onSaveInstanceState(outState);
		outState.putLong(ClassesDbAdapter.KEY_ROWID, _rowId);
	}

	/**
	 * Saves the data in case the application is suspended
	 */
	private void saveState() 
	{
		String course = _taskCourseText.getText().toString();
		String title = _taskTitleText.getText().toString();
		String dueDate = _taskDueDate.getText().toString();
		String body = _taskBodyText.getText().toString();

		if(course.length() == 0 ||
				title.length() == 0 ||
				dueDate.length() == 0 ||
				body.length() == 0 ||
				_confirmButton.isPressed() == false) 
		{
			Log.v(TAG,"Nothing in here returning nothing");
			return;
		}

		if (_rowId == null)  
		{
			course = course.replaceAll(" ", "");
			Log.v(TAG,"SAVING course: "+course);
			long id = _mDbHelper.createTask(course, title, dueDate, body);
			if (id > 0) 
			{
				_rowId = id;
			}
		} 
		else 
		{
			Log.v(TAG,"UPDATING course: "+course);
			_mDbHelper.updateTask(_rowId, course, title, dueDate, body);
		}
	}


	/* (non-Javadoc)
	 * @see android.app.Activity#onCreateDialog(int)
	 */
	@Override
	protected Dialog onCreateDialog(int id) 
	{
		switch (id) 
		{
		case TIME_DIALOG_ID:
			return new TimePickerDialog(this,
					mTimeSetListener, _hour, _minute, false);
		case DATE_DIALOG_ID:
			return new DatePickerDialog(this,
					mDateSetListener,
					_year, _month, _day);
		}
		return null;
	}

	/* (non-Javadoc)
	 * @see android.app.Activity#onPrepareDialog(int, android.app.Dialog)
	 */
	@Override
	protected void onPrepareDialog(int id, Dialog dialog) 
	{
		switch (id) 
		{
		case TIME_DIALOG_ID:
			((TimePickerDialog) dialog).updateTime(_hour, _minute);
			break;
		case DATE_DIALOG_ID:
			((DatePickerDialog) dialog).updateDate(_year, _month, _day);
			break;
		}
	}    

	/**
	 * Updates the date field with date
	 */
	private void updateDisplay() 
	{
		_taskDueDate.setText(
				new StringBuilder()
				// Month is 0 based so add 1
				.append(_month + 1).append("-")
				.append(_day).append("-")
				.append(_year).append(" ")
				.append(pad(_hour)).append(":")
				.append(pad(_minute)));
	}

	private DatePickerDialog.OnDateSetListener mDateSetListener =
		new DatePickerDialog.OnDateSetListener() 
	{

		public void onDateSet(DatePicker view, int year, int monthOfYear,
				int dayOfMonth) 
		{
			_year = year;
			_month = monthOfYear;
			_day = dayOfMonth;
			updateDisplay();
		}
	};

	private TimePickerDialog.OnTimeSetListener mTimeSetListener =
		new TimePickerDialog.OnTimeSetListener() 
	{

		public void onTimeSet(TimePicker view, int hourOfDay, int minute) 
		{
			_hour = hourOfDay;
			_minute = minute;
			updateDisplay();
		}
	};

	/**
	 * Convenience method used for padding date fields
	 * 
	 * @param c date integer
	 * @return
	 */
	private static String pad(int c) 
	{
		if (c >= 10)
			return String.valueOf(c);
		else
			return "0" + String.valueOf(c);
	}

}
